package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.moyun.modelclass.adapter.EditModelImageAdapter;
import com.moyun.modelclass.adapter.ModelAnnexAdapter;
import com.moyun.modelclass.base.BaseModelActivity;
import com.moyun.modelclass.dialog.ModelTypeDialog;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.OSSHelper;
import com.moyun.modelclass.http.api.AppModelDetailsApi;
import com.moyun.modelclass.http.api.CheckFileApi;
import com.moyun.modelclass.http.api.EditModelApi;
import com.moyun.modelclass.http.api.ModelRemoveApi;
import com.moyun.modelclass.http.api.ModelTypeApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.FileNewUtils;
import com.moyun.modelclass.utils.GlideEngine;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.moyun.modelclass.view.MyEditText;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;

import org.the3deer.util.android.ContentUtils;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 作者：Meteor
 * tip：编辑模型
 */
public class EditModelActivity extends BaseModelActivity implements ModelAnnexAdapter.OnFileDeleteClick {
    private RelativeLayout llEditModelTop;
    private ImageView ivEditModelBack;
    private ImageView ivEditModelDelete;

    private ImageView ivEditModelMainImage;
    private ImageView ivEditModelMainImageDelete;
    private FrameLayout flEditModelMainImageAdd;

    private MyEditText etEditModelTitle;
    private TextView etEditModelTitleLength;
    private EditText etEditModelContent;
    private ImageView ivEditModelAddImage;
    private View lineEditModelAddImage;
    private RecyclerView recyclerEditModelAddImage;
    private ImageView ivEditModelAddMainModel;
    private View lineEditModelAddMainModel;
    private RecyclerView recyclerEditModelAddMainModel;
    private ImageView ivEditModelAddAssistantModel;
    private View lineEditModelAddAssistantModel;
    private RecyclerView recyclerEditModelAddAssistantModel;
    private ImageButton ibEditModelOpen;
    private TextView etEditModelPriceUnit;
    private MyEditText etEditModelPrice;
    private ImageView etEditModelOriginal;
    private TextView tvEditModelType;
    private ImageView ivEditModelAddAnnex;
    private View lineEditModelAddAnnex;
    private RecyclerView recyclerEditModelAddAnnex;
    private TextView tvEditModelIssue;

    private String commentImageBean = "";//头图图片
    private String mModelId = "";//模型id
    private static final int REQUEST_CODE_LOAD_MAIN_STL_MODEL = 1101;//选择文件路径：模型完整体
    private static final int REQUEST_CODE_LOAD_ASSISTANT_STL_MODEL = 1102;//选择文件路径：模型分件
    private static final int REQUEST_CODE_LOAD_OTHER_MODEL = 1103;//选择文件路径：附件文件

    private static final int REQUEST_CODE_GENERATE_MAIN_STL_MODEL = 1201;//生成文件路径：模型完整体
    private static final int REQUEST_CODE_GENERATE_ASSISTANT_STL_MODEL = 1202;//生成文件路径：模型分件


    private EditModelImageAdapter modelDetailsImageAdapter = new EditModelImageAdapter();
    private EditModelImageAdapter mainModelSurfaceAdapter = new EditModelImageAdapter();
    private EditModelImageAdapter assistantModelSurfaceAdapter = new EditModelImageAdapter();
    private ModelAnnexAdapter modelAnnexAdapter = new ModelAnnexAdapter();

    public static final String KEY_EDIT_MODEL_URL = "KEY_EDIT_MODEL_URL";
    public static final String KEY_EDIT_MODEL_THUMBNAIL = "KEY_EDIT_MODEL_THUMBNAIL";

    private List<String> onePieceList = new ArrayList<>();//完整件或者组合件(模型完全体)
    private List<String> fileList = new ArrayList<>();//模型文件(模型分件)
    private List<String> otherFileList = new ArrayList<>();//额外文件

    private ModelTypeApi.BeanInfo mCheckBeanInfo = null;//模型分类
    private int mPosition = 0;//模型分类:位置

    private OSSHelper oSSHelper = null;

    private DecimalFormat df = new DecimalFormat("##0.00");


    public static void start(Context context, String modelId) {
        Intent starter = new Intent(context, EditModelActivity.class);
        starter.putExtra("modelId", modelId);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_edit_model;
    }

    @Override
    protected void assignViews() {
        llEditModelTop = (RelativeLayout) findViewById(R.id.ll_edit_model_top);
        ivEditModelBack = (ImageView) findViewById(R.id.iv_edit_model_back);
        ivEditModelDelete = (ImageView) findViewById(R.id.iv_edit_model_delete);
        ivEditModelMainImage = (ImageView) findViewById(R.id.iv_edit_model_main_image);
        ivEditModelMainImageDelete = (ImageView) findViewById(R.id.iv_edit_model_main_image_delete);
        flEditModelMainImageAdd = (FrameLayout) findViewById(R.id.fl_edit_model_main_image_add);

        etEditModelTitle = (MyEditText) findViewById(R.id.et_edit_model_title);
        etEditModelTitleLength = (TextView) findViewById(R.id.et_edit_model_title_length);

        etEditModelContent = (EditText) findViewById(R.id.et_edit_model_content);
        ivEditModelAddImage = (ImageView) findViewById(R.id.iv_edit_model_add_image);
        lineEditModelAddImage = (View) findViewById(R.id.line_edit_model_add_image);
        recyclerEditModelAddImage = (RecyclerView) findViewById(R.id.recycler_edit_model_add_image);
        ivEditModelAddMainModel = (ImageView) findViewById(R.id.iv_edit_model_add_main_model);
        lineEditModelAddMainModel = (View) findViewById(R.id.line_edit_model_add_main_model);
        recyclerEditModelAddMainModel = (RecyclerView) findViewById(R.id.recycler_edit_model_add_main_model);
        ivEditModelAddAssistantModel = (ImageView) findViewById(R.id.iv_edit_model_add_assistant_model);
        lineEditModelAddAssistantModel = (View) findViewById(R.id.line_edit_model_add_assistant_model);
        recyclerEditModelAddAssistantModel = (RecyclerView) findViewById(R.id.recycler_edit_model_add_assistant_model);
        ibEditModelOpen = (ImageButton) findViewById(R.id.ib_edit_model_open);


        etEditModelPriceUnit = (TextView) findViewById(R.id.et_edit_model_price_unit);
        etEditModelPrice = (MyEditText) findViewById(R.id.et_edit_model_price);
        etEditModelOriginal = (ImageView) findViewById(R.id.et_edit_model_original);
        tvEditModelType = (TextView) findViewById(R.id.tv_edit_model_type);
        ivEditModelAddAnnex = (ImageView) findViewById(R.id.iv_edit_model_add_annex);
        lineEditModelAddAnnex = (View) findViewById(R.id.line_edit_model_add_annex);
        recyclerEditModelAddAnnex = (RecyclerView) findViewById(R.id.recycler_edit_model_add_annex);
        tvEditModelIssue = (TextView) findViewById(R.id.tv_edit_model_issue);

        StatusBarUtil.setPaddingSmart(this, llEditModelTop);

        recyclerEditModelAddImage.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerEditModelAddImage.setAdapter(modelDetailsImageAdapter);

        recyclerEditModelAddMainModel.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerEditModelAddMainModel.setAdapter(mainModelSurfaceAdapter);

        recyclerEditModelAddAssistantModel.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerEditModelAddAssistantModel.setAdapter(assistantModelSurfaceAdapter);

        recyclerEditModelAddAnnex.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerEditModelAddAnnex.addItemDecoration(new DividerItemDecoration(
                this,
                Color.parseColor("#EEEEEE"),
                1,
                SizeUtils.dp2px(15),
                SizeUtils.dp2px(15)));
        modelAnnexAdapter.setOnFileDeleteClick(this);
        recyclerEditModelAddAnnex.setAdapter(modelAnnexAdapter);

        etEditModelTitleLength.setText(getString(R.string.evaluate_content_length, 0));
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivEditModelBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ClickUtils.applySingleDebouncing(ivEditModelDelete, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeModel();
            }
        });
        ClickUtils.applySingleDebouncing(flEditModelMainImageAdd, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitImage(true);
            }
        });

        ClickUtils.applySingleDebouncing(ivEditModelMainImageDelete, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentImageBean = "";
                Glide.with(EditModelActivity.this).clear(ivEditModelMainImage);
                flEditModelMainImageAdd.setVisibility(View.VISIBLE);
                ivEditModelMainImageDelete.setVisibility(View.GONE);
                ivEditModelMainImage.setVisibility(View.GONE);
            }
        });

        modelDetailsImageAdapter.setOnImageClick(new EditModelImageAdapter.OnImageClick() {
            @Override
            public void delete(int position) {
                modelDetailsImageAdapter.removeAt(position);
            }
        });

        mainModelSurfaceAdapter.setOnImageClick(new EditModelImageAdapter.OnImageClick() {
            @Override
            public void delete(int position) {
                onePieceList.remove(position);
                mainModelSurfaceAdapter.removeAt(position);
            }
        });

        assistantModelSurfaceAdapter.setOnImageClick(new EditModelImageAdapter.OnImageClick() {
            @Override
            public void delete(int position) {
                fileList.remove(position);
                assistantModelSurfaceAdapter.removeAt(position);
            }
        });

        etEditModelTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                etEditModelTitleLength.setText(getString(R.string.evaluate_content_length, s.toString().length()));
            }
        });

        etEditModelPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    etEditModelPriceUnit.setVisibility(View.VISIBLE);
                } else {
                    etEditModelPriceUnit.setVisibility(View.GONE);
                }
            }
        });

        ClickUtils.applySingleDebouncing(ivEditModelAddImage, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitImage(false);
            }
        });

        ClickUtils.applySingleDebouncing(ivEditModelAddMainModel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadMainSTLAll();
            }
        });

        ClickUtils.applySingleDebouncing(ivEditModelAddAssistantModel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadAssistantSTLAll();
            }
        });

        ibEditModelOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ibEditModelOpen.setSelected(!ibEditModelOpen.isSelected());
            }
        });

        etEditModelOriginal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etEditModelOriginal.setSelected(!etEditModelOriginal.isSelected());
            }
        });

        ClickUtils.applySingleDebouncing(tvEditModelType, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyHttp.post(EditModelActivity.this)
                        .api(new ModelTypeApi())
                        .request(new HttpCallback<HttpData<ModelTypeApi.Bean>>(EditModelActivity.this) {
                            @Override
                            public void onSucceed(HttpData<ModelTypeApi.Bean> result) {
                                if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                                    List<ModelTypeApi.BeanInfo> categoryList = result.getData().getList();
                                    categoryList.remove(0);
                                    ModelTypeDialog dialog = ModelTypeDialog.getInstance(mActivity, mPosition, categoryList, new ModelTypeDialog.OnProjectTypeListener() {
                                        @Override
                                        public void content(ModelTypeApi.BeanInfo checkBeanInfo, int position) {
                                            mCheckBeanInfo = checkBeanInfo;
                                            mPosition = position;
                                            tvEditModelType.setText(mCheckBeanInfo.getCategoryName());
                                        }

                                        @Override
                                        public void cancel() {

                                        }
                                    }).builder();
                                    dialog.show();
                                }
                            }
                        });
            }
        });

        ClickUtils.applySingleDebouncing(ivEditModelAddAnnex, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadOtherAll();
            }
        });

        ClickUtils.applySingleDebouncing(tvEditModelIssue, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitModel();
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
        mModelId = bundle.getString("modelId", "");
        if (mModelId == null || mModelId.isEmpty()) {
            ivEditModelDelete.setVisibility(View.GONE);
        } else {
            ivEditModelDelete.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initModelDetailsLog();
    }

    private void submitModel() {
        String title = etEditModelTitle.getText().toString().trim();
        String desc = etEditModelContent.getText().toString().trim();
        String price = etEditModelPrice.getText().toString().trim();

        if (commentImageBean.isEmpty()) {
            ToastUtils.showShort("请上传头图");
            return;
        }

        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("请输入文件名");
            return;
        }

        if (TextUtils.isEmpty(desc)) {
            ToastUtils.showShort("请输入模型描述");
            return;
        }

        if (fileList == null || fileList.size() <= 0) {
            ToastUtils.showShort("请选择模型分件");
            return;
        }

        if (TextUtils.isEmpty(price)) {
            ToastUtils.showShort("请输入模型价格");
            return;
        }

        if (mCheckBeanInfo == null) {
            ToastUtils.showShort("请选择模型分类");
            return;
        }


        initSaveModelApi(mModelId, commentImageBean, title, desc,
                modelDetailsImageAdapter.getData(), fileList, onePieceList, otherFileList,
                ibEditModelOpen.isSelected(), Double.parseDouble(price) * 100, etEditModelOriginal.isSelected(), Integer.parseInt(mCheckBeanInfo.getCategoryId()));
    }

    private void initSaveModelApi(String id, String simpleImage, String title, String desc,
                                  List<String> imageList, List<String> fileList, List<String> onePieceList, List<String> otherFileList,
                                  boolean isOpenFlag, double price, boolean isOriginal, int category) {
        EasyHttp.post(this).api(new EditModelApi()
                        .setId(id)
                        .setCoverImage(simpleImage)
                        .setTitle(title)
                        .setDesc(desc)
                        .setImages(imageList)
                        .setFiles(fileList)
                        .setOnePiece(onePieceList)
                        .setOtherFile(otherFileList)
                        .setOpenFlag(isOpenFlag)
                        .setPrice(price)
                        .setOriginal(isOriginal)
                        .setCategory(category))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        ToastUtils.showShort("发布成功");
                        finish();
                    }
                });
    }


    //上传stl文件：主文件
    private void uploadMainSTLAll() {
        XXPermissions.with(EditModelActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        ContentUtils.clearDocumentsProvided();
                        ContentUtils.setCurrentDir(null);
                        askForFile(REQUEST_CODE_LOAD_MAIN_STL_MODEL, "*/*");
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.showShort("获取存储权限失败");
                    }
                });
    }

    //上传stl文件：附件
    private void uploadAssistantSTLAll() {
        XXPermissions.with(EditModelActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        ContentUtils.clearDocumentsProvided();
                        ContentUtils.setCurrentDir(null);
                        askForFile(REQUEST_CODE_LOAD_ASSISTANT_STL_MODEL, "*/*");
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.showShort("获取存储权限失败");
                    }
                });
    }

    //上传其他文件
    private void uploadOtherAll() {
        XXPermissions.with(EditModelActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        ContentUtils.clearDocumentsProvided();
                        ContentUtils.setCurrentDir(null);
                        askForFile(REQUEST_CODE_LOAD_OTHER_MODEL, "*/*");
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.showShort("获取存储权限失败");
                    }
                });
    }

    private void askForFile(int requestCode, String mimeType) {
        Intent target = ContentUtils.createGetContentIntent(mimeType);
        Intent intent = Intent.createChooser(target, "Select file");
        try {
            startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        ContentUtils.setThreadActivity(this);
        if (resultCode != RESULT_OK) {
            return;
        }
        final Uri uri = data.getData();
        try {
            switch (requestCode) {
                case REQUEST_CODE_LOAD_MAIN_STL_MODEL:
                    if (uri != null) {
                        String mainStlPath = FileNewUtils.getFileAbsolutePath(this, uri);
                        if (!mainStlPath.toLowerCase().endsWith(".stl")) {
                            ToastUtils.showShort("请选择stl格式的文件");
                            return;
                        }
                        EditModelPreviewActivity.start(EditModelActivity.this, mainStlPath, REQUEST_CODE_GENERATE_MAIN_STL_MODEL);
                    }
                    break;
                case REQUEST_CODE_GENERATE_MAIN_STL_MODEL:
                    String mainUrl = data.getStringExtra(KEY_EDIT_MODEL_URL);
                    String mainThumbnail = data.getStringExtra(KEY_EDIT_MODEL_THUMBNAIL);
                    lineEditModelAddMainModel.setVisibility(View.VISIBLE);
                    onePieceList.add(mainUrl);
                    mainModelSurfaceAdapter.addData(mainThumbnail);
                    break;
                case REQUEST_CODE_LOAD_ASSISTANT_STL_MODEL:
                    if (uri != null) {
                        String assistantStlPath = FileNewUtils.getFileAbsolutePath(this, uri);
                        if (!assistantStlPath.toLowerCase().endsWith(".stl")) {
                            ToastUtils.showShort("请选择stl格式的文件");
                            return;
                        }
                        EditModelPreviewActivity.start(EditModelActivity.this, assistantStlPath, REQUEST_CODE_GENERATE_ASSISTANT_STL_MODEL);
                    }
                    break;
                case REQUEST_CODE_GENERATE_ASSISTANT_STL_MODEL:
                    String assistantUrl = data.getStringExtra(KEY_EDIT_MODEL_URL);
                    String assistantThumbnail = data.getStringExtra(KEY_EDIT_MODEL_THUMBNAIL);
                    lineEditModelAddAssistantModel.setVisibility(View.VISIBLE);
                    fileList.add(assistantUrl);
                    assistantModelSurfaceAdapter.addData(assistantThumbnail);
                    break;
                case REQUEST_CODE_LOAD_OTHER_MODEL:
                    if (uri == null) {
                        return;
                    }
                    String otherPath = FileNewUtils.getFileAbsolutePath(this, uri);
                    File otherFile = new File(otherPath);
                    String otherEncryptMD5 = EncryptUtils.encryptMD5File2String(otherPath);
                    String otherExtension = FileUtils.getFileExtension(otherPath);
                    long otherSize = FileUtils.getLength(otherFile);
                    EasyHttp.post(this)
                            .api(new CheckFileApi().setMd5(otherEncryptMD5).setExtName(otherExtension))
                            .request(new HttpCallback<HttpData<CheckFileApi.Bean>>(this) {
                                @Override
                                public void onSucceed(HttpData<CheckFileApi.Bean> md5Result) {
                                    Log.e("showProgressDialog==>", "执行了几次了：3");
                                    if (md5Result == null || md5Result.getData() == null) {
                                        return;
                                    }
                                    if (md5Result.getData().isExist()) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                lineEditModelAddAnnex.setVisibility(View.VISIBLE);
                                                otherFileList.add(md5Result.getData().getUrl());
                                                modelAnnexAdapter.addData(md5Result.getData().getFileName());
                                            }
                                        });
                                        return;
                                    }
                                    Log.e("showProgressDialog==>", "上传中：3");
                                    showProgressDialog();
                                    oSSHelper = OSSHelper.getInstance(new OSSHelper.OnOssUpLoadStateListener() {
                                        @Override
                                        public void onSuccess(PutObjectRequest request, PutObjectResult result, String fileId, String fileUrl) {
                                            Log.e("showProgressDialog==>", "上传成功：3");
                                            dismissProgressDialog();
                                            ToastUtils.showShort("上传成功");
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    lineEditModelAddAnnex.setVisibility(View.VISIBLE);
                                                    otherFileList.add(fileUrl);
                                                    modelAnnexAdapter.addData(FileUtils.getFileName(otherPath));
                                                }
                                            });
                                            if (oSSHelper != null) {
                                                oSSHelper.delete();
                                            }
                                        }

                                        @Override
                                        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                            ToastUtils.showShort("上传失败");
                                            Log.e("showProgressDialog==>", "上传失败：3");
                                            dismissProgressDialog();
                                        }
                                    });
                                    oSSHelper.init(EditModelActivity.this, true, otherExtension, otherPath, otherSize);
                                }
                            });
                    break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void submitImage(boolean isMain) {
        XXPermissions.with(EditModelActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        PictureSelector.create(EditModelActivity.this)
                                .openGallery(SelectMimeType.ofImage())
                                .setImageEngine(GlideEngine.createGlideEngine())
                                .setMaxSelectNum(1)
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(ArrayList<LocalMedia> result) {
                                        for (LocalMedia media : result) {
                                            Luban.with(EditModelActivity.this)
                                                    .load(media.getRealPath())
                                                    .ignoreBy(50)
                                                    .setTargetDir(CreateFileUtils.getSandboxPath(EditModelActivity.this))
                                                    .setCompressListener(new OnCompressListener() {
                                                                             @Override
                                                                             public void onStart() {
                                                                             }

                                                                             @Override
                                                                             public void onSuccess(int index, File compressFile) {
                                                                                 if (isMain) {
                                                                                     Glide.with(EditModelActivity.this)
                                                                                             .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                             .centerInside()
                                                                                             .diskCacheStrategy(DiskCacheStrategy.ALL)
                                                                                             .into(ivEditModelMainImage);
                                                                                 }

                                                                                 initUpdateImageApi(true, isMain, compressFile);
                                                                             }

                                                                             @Override
                                                                             public void onError(int index, Throwable e) {
                                                                             }
                                                                         }
                                                    ).launch();
                                        }
                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.showShort("获取存储权限失败");
                    }
                });
    }


    //模型详情
    private void initModelDetailsLog() {
        if (mModelId == null || mModelId.isEmpty()) {
            return;
        }
        EasyHttp.post(this)
                .api(new AppModelDetailsApi().setArticleId(mModelId))
                .request(new HttpCallback<HttpData<AppModelDetailsApi.Bean>>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(HttpData<AppModelDetailsApi.Bean> result) {
                        if (result != null && result.getData() != null) {
                            commentImageBean = result.getData().getCoverImage();
                            if (commentImageBean == null || commentImageBean.isEmpty()) {
                                flEditModelMainImageAdd.setVisibility(View.VISIBLE);
                                ivEditModelMainImageDelete.setVisibility(View.GONE);
                                ivEditModelMainImage.setVisibility(View.GONE);
                            } else {
                                flEditModelMainImageAdd.setVisibility(View.GONE);
                                ivEditModelMainImageDelete.setVisibility(View.VISIBLE);
                                ivEditModelMainImage.setVisibility(View.VISIBLE);
                            }

                            Glide.with(EditModelActivity.this)
                                    .asBitmap()
                                    .load(CommonConfiguration.splitResUrl(5, result.getData().getCoverImage()))
                                    .centerInside()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .into(new BitmapImageViewTarget(ivEditModelMainImage) {
                                        @Override
                                        protected void setResource(Bitmap resource) {
                                            super.setResource(resource);
                                            ivEditModelMainImage.setImageBitmap(ImageUtils.toRoundCorner(resource, 10f));
                                        }
                                    });

                            etEditModelTitle.setText(result.getData().getTitle());
                            etEditModelContent.setText(result.getData().getDesc());

                            modelDetailsImageAdapter.addData(result.getData().getImages());
                            if (result.getData().getOneStlPieces() != null && result.getData().getOneStlPieces().size() > 0) {
                                for (AppModelDetailsApi.StlFilesBean stlFilesBean : result.getData().getOneStlPieces()) {
                                    onePieceList.add(stlFilesBean.getFile());
                                    mainModelSurfaceAdapter.addData(stlFilesBean.getThumbnail());
                                }
                            }

                            if (result.getData().getStlFiles() != null && result.getData().getStlFiles().size() > 0) {
                                for (AppModelDetailsApi.StlFilesBean stlFilesBean : result.getData().getStlFiles()) {
                                    fileList.add(stlFilesBean.getFile());
                                    assistantModelSurfaceAdapter.addData(stlFilesBean.getThumbnail());
                                }
                            }

                            ibEditModelOpen.setSelected(result.getData().isOpenFlag());
                            etEditModelPrice.setText(df.format(result.getData().getPrice() * 0.01));
                            etEditModelOriginal.setSelected(result.getData().isOriginal());
                            initModelType(result.getData().getCategory());
                            if (result.getData().getOtherFiles() != null && result.getData().getOtherFiles().size() > 0) {
                                for (AppModelDetailsApi.OtherFilesBean otherFilesBean : result.getData().getOtherFiles()) {
                                    otherFileList.add(otherFilesBean.getFile());
                                    modelAnnexAdapter.addData(otherFilesBean.getFileName());
                                }
                            }
                        }
                    }
                });
    }

    private void initModelType(String categoryId) {
        EasyHttp.post(EditModelActivity.this)
                .api(new ModelTypeApi())
                .request(new HttpCallback<HttpData<ModelTypeApi.Bean>>(EditModelActivity.this) {
                    @Override
                    public void onSucceed(HttpData<ModelTypeApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            for (ModelTypeApi.BeanInfo data : result.getData().getList()) {
                                if (data.getCategoryId().equals(categoryId)) {
                                    mCheckBeanInfo = data;
                                    tvEditModelType.setText(mCheckBeanInfo.getCategoryName());
                                }
                            }
                        }
                    }
                });
    }

    private void initUpdateImageApi(boolean isWatermark, boolean isMain, File imageFile) {
        EasyHttp.post(this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(imageFile)
                        .setWatermark(isWatermark))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        if (isMain) {
                            if (commentImageBean == null || commentImageBean.isEmpty()) {
                                commentImageBean = result.getData().getUrl();
                            }

                            if (commentImageBean == null || commentImageBean.isEmpty()) {
                                flEditModelMainImageAdd.setVisibility(View.VISIBLE);
                                ivEditModelMainImageDelete.setVisibility(View.GONE);
                                ivEditModelMainImage.setVisibility(View.GONE);
                            } else {
                                flEditModelMainImageAdd.setVisibility(View.GONE);
                                ivEditModelMainImageDelete.setVisibility(View.VISIBLE);
                                ivEditModelMainImage.setVisibility(View.VISIBLE);
                            }
                        } else {
                            lineEditModelAddImage.setVisibility(View.VISIBLE);
                            modelDetailsImageAdapter.addData(result.getData().getUrl());
//                            etEditArticleContent.insertImage(CommonConfiguration.splitResUrl(3, result.getData().getUrl()));
                        }
                    }
                });
    }

    private void removeModel() {
        EasyHttp.post(this)
                .api(new ModelRemoveApi().setModelId(mModelId))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        ToastUtils.showShort("删除成功");
                        finish();
                    }
                });
    }

    @Override
    public void delete(int position) {
        otherFileList.remove(position);
        if (otherFileList != null && otherFileList.size() > 0) {
            modelAnnexAdapter.setNewInstance(otherFileList);
        } else {
            lineEditModelAddAnnex.setVisibility(View.GONE);
            modelAnnexAdapter.setNewInstance(new ArrayList<>());
        }
    }
}
